package com.dudu.access;

import java.util.Calendar;

import net.sf.json.JSONObject;

import org.apache.commons.lang.StringUtils;

import com.dudu.bean.ResponseSendVoiceBean;
import com.dudu.enumeration.RemindEnum;
import com.dudu.service.ILogService;
import com.dudu.service.impl.LogService;
import com.dudu.utils.DateUtils;
import com.dudu.utils.DictionaryUtils;
import com.dudu.utils.EncryptUtil;
import com.dudu.utils.HttpRequest;

import core.CoreService;

/**
 * 天润融通
 * 
 * @author qinfx
 * 
 */
public class TianRunUtil {

    private static ILogService logService = new LogService();
    private static String ServerUrl = DictionaryUtils.getValueByTypeAndKey("tianRun", "url");
    private static String token = DictionaryUtils.getValueByTypeAndKey("tianRun", "token");
    private static String appId = DictionaryUtils.getValueByTypeAndKey("tianRun", "appId");

    /*** 正式 **/
    // private static String ServerUrl="http://api.vlink.cn/interface/open/v1";
    // private static String token="38e5356fd1d6a99626afc6b9cbde5dbd";
    // private static String appId="5000446";
    /*** 沙箱 **/
    // private static String ServerUrl="http://api.vlink.cn/interface/open/v1";
    // private static String token="6d5d22cb2fa35536aeeb93e89214dfd8";
    // private static String appId="5000445";
    /** 测试 **/
    // private static String ServerUrl="http://api.vlink.cn/interface/open/v1";
    // private static String token="769006fdfef6f5bdb566697c0c463e59";
    // private static String appId="5000435";
    public static void main(String[] agr) throws Exception {
	voiceNotice("17001090120", "在未返回结果信息前可以给予提示前可前", "02151306449", "", "");
	// billAndStatus();
    }

    /**
     * 外呼（语音通知）
     * 
     * @param called
     *            外呼号码
     * @param mediaTxt
     *            外呼内容：文字
     * @param displayNum
     *            显号
     * @param userData
     *            自定义内容
     * @param txt
     *            前导音
     * @return
     */
    public static ResponseSendVoiceBean voiceNotice(String called, String mediaTxt, String displayNum, String userData, String txt) {
	ResponseSendVoiceBean responseSendVoice = new ResponseSendVoiceBean();
	long begin = Calendar.getInstance().getTimeInMillis();
	String responsedata = "";
	String result = "-1";
	String sessionid = "";
	String desc = "";
	StringBuffer paramBuffer = new StringBuffer("");
	try {
	    String timestamp = String.valueOf(System.currentTimeMillis() / 1000);

	    paramBuffer.append("appId=" + appId);
	    paramBuffer.append("&timestamp=" + timestamp);
	    paramBuffer.append("&sign=" + EncryptUtil.class.newInstance().md5Digest(appId + token + timestamp).toLowerCase());
	    paramBuffer.append("&tel=" + called);
	    paramBuffer.append("&userField=" + userData);
	    paramBuffer.append("&uniqueId=" + "");// sessionId
	    paramBuffer.append("&timeout=" + "");// 超时时间
	    paramBuffer.append("&delay=" + "");// 播放几次
	    paramBuffer.append("&clid=" + displayNum); // 显号 "02151397763"
	    if (StringUtils.isBlank(txt)) {
		paramBuffer.append("&message=" + mediaTxt.replaceAll("\r|\n|\t", ""));
	    } else {
		paramBuffer.append("&message=" + txt + "," + mediaTxt.replaceAll("\r|\n|\t", ""));// 前导音+内容，加逗号为了停顿
	    }

	    String Myurl = ServerUrl + "/webcall?";
	    responsedata = HttpRequest.getData(Myurl + paramBuffer.toString());
	    remind(responsedata, RemindEnum.OPEN_VOICE_TIANRUN.getKey(), RemindEnum.OPEN_VOICE_TIANRUN.getValue());
	    CoreService.log.info("天润融通 voiceNotice req:" + Myurl + paramBuffer.toString() + "---response:" + responsedata);
	    if (StringUtils.isNotBlank(responsedata)) {
		JSONObject response = JSONObject.fromObject(responsedata);
		result = response.optString("result");
		desc = response.optString("description");
		if (result.equals("0")) {
		    result = "0";
		    sessionid = response.optString("uniqueId");
		}
	    } else {
		responsedata = "";
	    }

	} catch (Exception e) {
	    e.printStackTrace();
	    responseSendVoice.setResult("9999");
	    responseSendVoice.setDesc(e.getMessage());
	    responseSendVoice.setSessionid("");
	    return responseSendVoice;
	}
	long end = Calendar.getInstance().getTimeInMillis();
	Double time = Double.valueOf((end - begin)) / 1000;
	logService.logIms(time, "TianRunNotice", "【" + paramBuffer.toString() + "】", "【" + responsedata + "】", result, DateUtils.getCurrentTime(), "TianRun", called);
	responseSendVoice.setResult(result);
	responseSendVoice.setSessionid(sessionid);
	responseSendVoice.setDesc(desc);
	return responseSendVoice;
    }

    /**
     * 提醒
     * 
     * @param response
     * @param abilityType
     */
    public static void remind(String response, String abilityType, String content) {
	if (StringUtils.isNotBlank(response)) {
	    JSONObject responsejson = JSONObject.fromObject(response);
	    String result = responsejson.optString("result");
	    String desc = responsejson.optString("description");
	    if (StringUtils.isBlank(result)) {
		RemindUtils.remind(abilityType, content + ":" + response, "sms");
	    } else if (result.equals("1")) {//1为失败,0为成功
		if (desc.contains("无效的clid")) {
		    RemindUtils.remind(abilityType, content + ":" + desc, "sms");
		} else if (desc.contains("请求频度过高")) {
		    RemindUtils.remind(abilityType, content + ":" + desc, "sms");
		}else{
		   // RemindUtils.remind(abilityType, content + ":" + desc, "email2"); 
		}
	    }

	} else {
	    RemindUtils.remind(abilityType, content + ":接口响应为空", "sms");
	}
    }

}
